import { Controller } from 'egg';

export default class PetController extends Controller {

  // 展示所有仓库中的宠物信息/分页展示
  public async index() {
    const { ctx } = this
    const { currentPage, pageSize, name } = ctx.queries
    let pets
    if (name[0] != 'undefined' && name[0] != '') {
      pets = await ctx.service.pet.selectLikeName(name[0])
    } else {
      pets = await ctx.service.pet.selectAll()
    }

    const total = pets.length
    // 分页
    const pageData = pets.splice(Number(Number(currentPage) - 1) * Number(pageSize),
         Number(pageSize))

    ctx.body = {
      code: 2000,
      pageData,
      total
    }
  }

  // 添加pet
  public async new() {
    const { ctx } = this
    const { pet } = ctx.request.body
    await ctx.service.pet.addOne(pet)
    ctx.body = {
      code: 2000,
      msg: '添加成功',
    }
  }

  // 删除pet
  public async destroy() {
    const { ctx } = this
    const { id } = ctx.queries
    const res = await ctx.service.pet.delById(id)
    let msg = ''
    if (res.affectedRows > 0) {
      msg = '删除成功'
    } else {
      msg = '删除失败'
    }
    ctx.body = {
      code: 2000,
      msg,
    }
  }

  // 修改pet
  public async update() {
    const { ctx } = this
    const { pet } = ctx.request.body
    const res = await ctx.service.pet.updateById(pet)
    let msg = '修改失败'
    if (res.affectedRows > 0) {
      msg = '修改成功'
    }
    ctx.body = {
      code: 2000,
      msg
    }
  }
}